﻿using FalconSystemAndroidProtocol.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Net;

namespace FalconSystemAndroidProtocol.Controllers
{
    public class TrackDataController : ApiController
    {
        /// <summary>
        /// Permite registrar los puntos gps al trackData
        /// </summary>
        /// <param name="param"></param>
        /// <returns>Retorna los puntos gps registrados para eliminarlos en el app</returns>
        [HttpPost, ActionName("Insert")]
        public ObjectResult<TrackDataResult> Insert(TrackDataParam param)
        {
            ObjectResult<TrackDataResult> result = new ObjectResult<TrackDataResult>();
            TrackDataResult data = new TrackDataResult();
            try
            {
                foreach(TrackData item in param.trackDataList){
                    try
                    {
                        var trackData = new EntityFramework.TrackData();
                        using(var entity = new EntityFramework.FalconSystemDBEntities()){
                            trackData = new EntityFramework.TrackData();
                            
                            trackData.GPSImei = item.imei;
                            trackData.Heading = item.heading;
                            trackData.Latitude = item.latitude;
                            trackData.Longitude = item.longitude;
                            trackData.Speed = item.speed;
                            trackData.Type = item.type;
                            trackData.DateTime = item.datetime;

                            entity.TrackData.Add(trackData);
                            entity.SaveChanges();
                        }
                        data.trackDataList.Add(new TrackDataStatus() { trackDataID = item.trackDataID, imei = item.imei, datetime = item.datetime});
                    }
                    catch (Exception ex) {
                        if(!ex.InnerException.ToString().Contains("PRIMARY KEY"))
                            data.trackDataList.Add(new TrackDataStatus() { trackDataID = item.trackDataID, imei = item.imei, datetime = item.datetime, isSuccessful = false, description = ex.Message });
                        else
                            data.trackDataList.Add(new TrackDataStatus() { trackDataID = item.trackDataID, imei = item.imei, datetime = item.datetime});
                    }
                }
                
                data.trackDataListTotal = data.trackDataList.Count;
                result.data = data;
            }
            catch (Exception ex) {
                result.code = "99";
                result.description = "No se registro los puntos gps";
                result.descriptionDetail = ex.Message;
                result.isSuccessful = false;
            }
            return result;
        }
        
    }
}
